<?php
declare(strict_types=1);

namespace app\common\business;

use app\common\model\mysql\GoodsSku as GoodsSkuModel;
use think\Exception;

class GoodsSku extends BusiBase
{
    public function __construct()
    {
        $this->model = new GoodsSkuModel();
    }

    /**
     * 商品规格属性批量添加
     *
     * @param $data
     * @return false|\think\Collection
     */
    public function saveAll(array $data)
    {
        if (!$data['skus']) return false;

        $addData = [];
        foreach ($data['skus'] as $value) {
            $addData[] = [
                'goods_id'        => $data['goods_id'],
                'specs_value_ids' => $value['propvalnames']['propvalids'],
                'price'           => $value['propvalnames']['skuSellPrice'],
                'cost_price'      => $value['propvalnames']['skuMarketPrice'],
                'stock'           => $value['propvalnames']['skuStock'],
                'status'          => config('status.mysql.table_normal')
            ];
        }

        try{
            $insert = $this->model->saveAll($addData);
        } catch (\Exception $e) {
            $this->errorLog("insert data :". json_encode($addData));
            $this->errorLog("insert data error: ".$e->getMessage());
            throw new Exception('sku添加失败');
        }
        return $insert->toArray();
    }

    /**
     * 根据 sku Id 查找 sku 及商品信息
     *
     * @param int $id
     * @return GoodsSkuModel|array|\think\Model|null
     */
    public function getNormalSkuAndGoods(int $id)
    {
        try {
            $result = $this->model->with('goods')->find($id);
        } catch (\Exception $e) {
            $this->errorLog("find sku and goods error: ".$e->getMessage());
            return [];
        }
        if (empty($result) || $result['status'] != config('status.mysql.table_normal')) return [];
        return $result;
    }

    /**
     * 通过商品 ID 获取 sku 数据
     *
     * @param int $goodsId
     * @return array
     */
    public function getNormalSkuByGoodsId(int $goodsId = 0)
    {
        if (!$goodsId) return [];
        try {
            $result = $this->model->getNormalSkuByGoodsId($goodsId);
        } catch (\Exception $e) {
            $this->errorLog("find sku by goods_id $goodsId error :".$e->getMessage());
            return [];
        }
        return $result->toArray();
    }

    /**
     * 批量更新 sku 库存
     *
     * @param array $data
     * @return false|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateMoreStock(array $data)
    {
        // 提取待修改数据 id
        $ids      = array_keys($data);
        try {
            // 查找待修改数据
            $skuRes   = $this->model->getNormalByIdArr($ids, 'id,stock');
        } catch (\Exception $e) {
            $this->errorLog('get normal by idarr error: '.$e->getMessage());
            throw new Exception('服务器内部错误');
        }
        if (!$skuRes) return false;
        $skuResult = $skuRes->toArray();
        $skuData  = array_column($skuResult, 'stock', 'id');
        // 组装待修改数据数组
        $update   = [];
        foreach ($data as $key=>$val) {
            $update[] = [
                'id' => $key,
                'stock' => $skuData[$key] - $val
            ];
        }
        try {
            $editAll = $this->model->saveAll($update);
        } catch (\Exception $e) {
            $this->errorLog('edit '.json_encode($update).' error: '.$e->getMessage());
            throw new Exception('服务器内部错误');
        }
        return $editAll;
    }
}